﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core
{
    public abstract class EntityModel : IValidation
    {       
        private List<ValidationResult> _validationResults = new List<ValidationResult>();

        private bool _isValidated = false;

        public bool IsValid
        {
            get
            {
                if (_isValidated)
                {
                    return _validationResults.Count==0 ? true : false;
                }
                else
                {
                    this.Validate();
                    return this.IsValid;
                }
            }           
        }
        
        public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> ValidationResults
        {
            get
            {
                return _validationResults;
            }
            set
            {
                foreach (var result in value)
                {
                    _validationResults.Add(result);
                }
            }
        }

        public string ValidationResultsString
        {
            get
            {
                var sb = new StringBuilder();

                foreach (var validationResult in this.ValidationResults)
                {
                    sb.AppendFormat("{0}{1}", validationResult.ErrorMessage, Environment.NewLine);
                }

                return sb.ToString();
            }          
        }

        protected virtual void Validate()
        {
            Validator.TryValidateObject(this, new ValidationContext(this), _validationResults, true);
            _isValidated = true;
        }

        protected void ValidateCollection(ICollection<EntityModel> collection)
        {
            foreach (var entity in collection)
            {
                if (!entity.IsValid)
                {
                    this.ValidationResults = entity.ValidationResults;
                }
            }
        }
    }
}
